//
//  TTEmotionItem.swift
//  TTProduct
//
//  Created by Toj on 3/29/21.
//  Copyright © 2021 TTProduct. All rights reserved.
//

import Cocoa

class TTEmotionItem: NSCollectionViewItem {
    var emoticon: TTEmoticon? {
        didSet {
            let imagePath = emoticon?.imagePath ?? ""
            emojiImageView.image = NSImage(contentsOfFile: imagePath)
        }
    }
    
    private lazy var backgroundView: NSView = {
        let view = NSView()
        return view
    }()
    
    private lazy var emojiImageView: NSImageView = {
        let view = NSImageView()
        return view
    }()
    
    private var trackingArea: NSTrackingArea?
    override func loadView() {
        view = NSView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(backgroundView)
        view.addSubview(emojiImageView)
        
        backgroundView.snp.makeConstraints { (make) in
            make.center.equalTo(view)
            make.width.height.equalTo(36)
        }
        
        emojiImageView.snp.makeConstraints { (make) in
            make.center.equalTo(view)
            make.width.height.equalTo(24)
        }
        
        backgroundView.tt_backgroundColor = NSColor.white
        backgroundView.tt_cornerRadius(6)
    }
    
    override func viewDidLayout() {
        super.viewDidLayout()
        
        backgroundView.trackingAreas.forEach { (area) in
            view.removeTrackingArea(area)
        }
        let aOptions: NSTrackingArea.Options = [.mouseEnteredAndExited,
                                                .mouseMoved,
                                                .cursorUpdate,
                                                .activeAlways
        ]
        trackingArea = NSTrackingArea(rect: view.bounds, options: aOptions, owner: self, userInfo: nil)
        backgroundView.addTrackingArea(trackingArea!)
    }
    
    override var isSelected: Bool {
        set {
            super.isSelected = false
        }
        get { return super.isSelected }
    }
}

// MARK: - Class Override Event
extension TTEmotionItem {
    
    // 鼠标进入
    override func mouseEntered(with event: NSEvent) {
        super.mouseEntered(with: event)
        backgroundView.tt_backgroundColor = NSColor.init(hexColor: "#F0F0F0")
    }
    
    // 鼠标左键按下
    override func mouseDown(with event: NSEvent) {
        super.mouseDown(with: event)
        backgroundView.tt_backgroundColor = NSColor.init(hexColor: "#DFDFDF")
    }
    
    // 鼠标左键抬起
    override func mouseUp(with event: NSEvent) {
        super.mouseUp(with: event)
        backgroundView.tt_backgroundColor = .white
    }

    // 鼠标离开
    override func mouseExited(with event: NSEvent) {
        super.mouseExited(with: event)
        
        backgroundView.tt_backgroundColor = .white
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
    }
}
